package cn.iocoder.yudao.module.reading.service.user;

import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserSettingsUpdateReqVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.user.UserSettingsDO;
import cn.iocoder.yudao.module.reading.dal.mysql.user.UserSettingsMapper;
import cn.iocoder.yudao.module.reading.enums.common.ReadingModeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;

/**
 * 用户设置 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class UserSettingsServiceImpl implements UserSettingsService {

    @Resource
    private UserSettingsMapper userSettingsMapper;

    @Override
    public UserSettingsDO getUserSettings(Long userId) {
        UserSettingsDO settings = userSettingsMapper.selectByUserId(userId);
        if (settings == null) {
            // 如果用户设置不存在，创建默认设置
            settings = createDefaultUserSettings(userId);
        }
        return settings;
    }

    @Override
    public void updateUserSettings(Long userId, UserSettingsUpdateReqVO updateReqVO) {
        UserSettingsDO settings = userSettingsMapper.selectByUserId(userId);
        if (settings == null) {
            // 如果用户设置不存在，先创建默认设置
            settings = createDefaultUserSettings(userId);
        }

        // 更新设置
        UserSettingsDO updateObj = UserSettingsDO.builder()
                .id(settings.getId())
                .readingMode(updateReqVO.getReadingMode())
                .autoTurnPage(updateReqVO.getAutoTurnPage())
                .turnPageDelay(updateReqVO.getTurnPageDelay())
                .autoPlayAudio(updateReqVO.getAutoPlayAudio())
                .autoTurnAfterAudio(updateReqVO.getAutoTurnAfterAudio())
                .autoReadNext(updateReqVO.getAutoReadNext())
                .build();

        userSettingsMapper.updateById(updateObj);
    }

    @Override
    public UserSettingsDO createDefaultUserSettings(Long userId) {
        UserSettingsDO settings = UserSettingsDO.builder()
                .userId(userId)
                .readingMode(ReadingModeEnum.IMAGE.getCode())
                .autoTurnPage(false)
                .turnPageDelay(10)
                .autoPlayAudio(true)
                .autoTurnAfterAudio(true)
                .autoReadNext(false)
                .build();

        userSettingsMapper.insert(settings);
        return settings;
    }

}
